// manager/pages/execute/index.js
import { getSystemInfo } from '../../../utils/getSystemInfo';
import { request } from '../../../utils/request';
import WxValidate from '../../../common/WxValidate';
import util from '../../../common/util'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        cardNum: "",
        userInfo: {},
        // 营销方式
        semWay: [],
        // 营销结果
        semResult: [],
        // 客户标签
        custTag: [],
        // 日期限制
        startDate: "",
        endDate: "",
        // 客户标签选择结果
        custTagResult: [],
        semForm: {
            cardNum: "",
            semWay: "",
            semResult: "",
            semNumbers: "",
            followTime: "",
            custTitle: "",
            semMemo: "",
        },
        show: false,
        actions: [],
        activeIndex: 0,
        tabList: [
            {
				id: 1,
                text: "客户信息"
            },
            {
				id: 2,
                text: "任务营销记录"
            }
        ],
        isViewInfo: false,
        info: {},
        semRecordList: []
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if(options.cardNum){
            this.setData({
                cardNum: options.cardNum
            })
        }
        this.setData({
            startDate: util.formatDate(new Date()),
            endDate: util.formatDate(new Date(),100)
        })
        this.initValidate();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        this.getUserInfo();
        this.getDictionaryInfo();
        this.getTaskInfo();
        this.getCustSemList();        
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 输入框输入时
     */
    input(e){
        let key = e.target.dataset.key;
        this.setData({
            ['semForm.'+key]: e.detail.value
        })
    },

    /**
     * 选择框变化时
     */
    pickerChagne(e){
        let { key, value } = e.detail;
        let { semForm } = this.data;
        if(key=="semResult"&&value!=3){
            semForm.followTime = "";
        }
        semForm[key] = value;
        this.setData({
            semForm
        })
    },

    /**
     * 查看关闭详细信息
     */
    changeViewInfo(e){
        let { isViewInfo } = this.data;
        this.setData({
            isViewInfo: !isViewInfo
        })
    },
    /**
     * 日期选择
     */
    bindDateChange: function(e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            ['semForm.followTime']: e.detail.value
        })
    },
    /**
     * 客户标签选择
     */
    onCheckboxChange(event) {
        this.setData({
            custTagResult: event.detail,
            ['semForm.custTitle']: event.detail.join(",")
        });
    },

    // 获取当前登录者的用户信息
    getUserInfo(e) {        
        request({
            url: "/user/getUserInfo",
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {}
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    userInfo: res.data.userInfo
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    /**
     * 获取营销方式、营销结果、客户标签字典
     */
    getDictionaryInfo() {
        request({
            url: "/commonApi/getDictionaryInfo",
            method: "GET",
            data: {
				dictType: "cif_sem_way"
			}
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    semWay: res.data
                })
            }
            return request({
                url: "/commonApi/getDictionaryInfo",
                method: "GET",
                data: {
                    dictType: "cif_sem_result"
                }
            })
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    semResult: res.data
                })
            }
            return request({
                url: "/commonApi/getDictionaryInfo",
                method: "GET",
                data: {
                    dictType: "cif_cust_title"
                }
            })
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    custTag: res.data
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    /**
     * 获取详情信息
     */
    getTaskInfo(){
        request({
            url: `/marketing/semTaskInfo`,
            // header: {
            //     "content-type": "application/x-www-form-urlencoded"
            // },
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {
                cardNum: this.data.cardNum
            }
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    info: res.data
                })
            }
        }).catch(error => {
            // console.log(error)
        })	
    },
    /**
     * 获取任务营销记录
     */
    getCustSemList(){
        request({
            url: `/marketing/getCustSemList`,
            // header: {
            //     "content-type": "application/x-www-form-urlencoded"
            // },
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {
                cardNum: this.data.cardNum
            }
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    semRecordList: res.data
                })
            }
        }).catch(error => {
            // console.log(error)
        })	
    },

    /**
     * 拨打电话
     */
    makePhoneCall(e) {
        let { tel } = e.currentTarget.dataset;
        if(!tel){
            wx.showToast({
                title: "暂无联系方式",
                icon: 'none',
                duration: 2000
            })
            return
        }
        getSystemInfo({
            android: () => {
                let actions = [
                    { name: tel, color: '#999', disabled: true },
                    { name: '呼叫', color: '#000' },
                ]
                this.setData({
                    show: true,
                    actions
                })
            },
            ios: () => {
                wx.makePhoneCall({
                    phoneNumber: tel
                })
            }
        })
    },

    /**
     * 复制电话
     */
    copy(e){
        let { tel } = e.currentTarget.dataset;
        wx.setClipboardData({
            data: tel,
            success (res) {
                wx.hideToast()
                wx.showToast({
                    title: "电话已复制",
                    icon: 'none',
                    duration: 2000
                });
            }
        })
    },

    tabChange(e){
        let { index } = e.detail;
        this.setData({
            activeIndex: index
        })
	},

    /**
     * 保存
     */
    save(e){
        let { cardNum, semForm } = this.data;
        semForm.cardNum = cardNum;
        if(!semForm.semWay){
            this.showModal({msg: '请选择营销方式'})
            return false
        }
        if(!semForm.semResult){
            this.showModal({msg: '请选择营销结果'})
            return false
        }
        // 传入表单数据，调用验证方法
        if (semForm.semResult == 1 && !this.WxValidate.checkForm(semForm)) {
            const error = this.WxValidate.errorList[0]
            this.showModal(error)
            return false
        }else{
            semForm.semNumbers = '';
        }
        if (semForm.semResult == 3 && !semForm.followTime) {
            this.showModal({msg: '请选择跟进时间'})
            return false
        }
        request({
            url: `/marketing/addSemExecuteRecord`,
            data: semForm
        }).then(res => {
            if(res.code == 0){
                wx.showToast({
                    title: '保存成功',
                    icon: 'none',
                    mask: true,
                    duration: 2000
                });
                setTimeout(()=>{
                    wx.navigateBack({
                      delta: 1,
                    })
                },2000)
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    // 表单验证
    initValidate() {
        // 验证字段的规则
        const rules = {
            semNumbers: {
                required: true,
                digits: true,
                min: 1
            }
        }
        // 验证字段的提示信息，若不传则调用默认的信息
        const messages = {
            semNumbers: {
                required: '请输入营销数量',
                digits: '营销数量为数字',
                min: '营销数量不小于1'
            }
        }
        // 创建实例对象
        this.WxValidate = new WxValidate(rules, messages)
    },
    showModal(error) {
        wx.showToast({
            title: error.msg,
            icon: 'none',
            duration: 2000
        })
    },
    onSelect(e) {
        console.log(e)
        this.setData({
            show: false
        })
        wx.makePhoneCall({
            phoneNumber: this.data.info.telNo
        })
    },
    onCancel() {
        this.setData({ show: false });
    },
})